const Author = require('../models/author');
const Book = require('../models/book');
const async = require('async');
const {body,validationResult} = require('express-validator/check');
const {sanitizeBody} = require('express-validator/filter');

//author list
exports.author_list = (req,res,next)=>{
    Author.find().sort([['family_name','ascending']]).exec(function (err,list_authors) {
        if(err){
            return next(err);
        }else{
            res.render('author_list',{title:'作者列表',author_list:list_authors})
        }
    })
};

//author detail
exports.author_detail = (req,res,next)=>{
    async.parallel({
        author:function (cb) {
            Author.findById(req.params.id).exec(cb);
        },
        author_books:function (cb) {
            Book.find({author:req.params.id},'title summary')
                .exec(cb);
        }
    },function (err, results) {
        if(err||results.author==null){
            if(results.author==null){
                err = new Error('Author not found');
                err.statusCode = 404;
            }
            next(err);
        }else{
            res.render('author_detail',{
                title:'当前作家：'+results.author.name,
                author:results.author,
                author_books:results.author_books
            })
        }
    });
};

//author create form page
exports.author_create_get = (req,res)=>{
    res.render('author_form',{title:'作家创建'})
};

//author create post
exports.author_create_post = [
    body('first_name').isLength({min:1}).trim().withMessage('名字必填'),
    body('family_name').isLength({min:1}).trim().withMessage('姓氏必填'),
    body('date_of_birth','出生年月不合法').optional({checkFalsy:true}).isISO8601(),
    body('date_of_death','死亡年月不合法').optional({checkFalsy:true}).isISO8601(),
    sanitizeBody('first_name').escape(),
    sanitizeBody('family_name').escape(),
    sanitizeBody('date_of_birth').toDate(),
    sanitizeBody('date_of_death').toDate(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let author = new Author({
            first_name:req.body.first_name,
            family_name:req.body.family_name,
            date_of_birth:req.body.date_of_birth,
            date_of_death:req.body.date_of_death
        });
        if(!errors.isEmpty()){
            res.render('author_form',{title:'作家创建',author,errors:errors.array()})
        }else{
            author.save(function (err) {
                if(err){
                    next(err)
                }else{
                    res.redirect(author.url);
                }
            })
        }
    }
];

//author delete get
exports.author_delete_get = (req,res,next)=>{
    async.parallel({
        author:function (cb) {
            Author.findById(req.params.id).exec(cb);
        },
        author_books:function (cb) {
            Book.find({author:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        if(results.author==null){
            res.redirect('/catalog/authors');
        }else{
            res.render('author_delete',{'title':'删除作家',author:results.author,author_books:results.author_books})
        }
    })
};

//author delete post
exports.author_delete_post = (req,res,next)=>{
    async.parallel({
        author_books:function (cb) {
            Book.find({author:req.body.authorid}).exec(cb);
        },
        author:function (cb) {
            Author.findById(req.body.authorid).exec(cb)
        }
    },function (err, results) {
       if(err) return next(err);
       if(results.author_books.length>0){
           res.render('author_delete',{title:'删除失败',author:results.author,author_books:results.author_books})
       }else{
           Author.findByIdAndRemove(req.body.authorid).exec(function (err) {
               if(err) return next(err);
               res.redirect('/catalog/authors');
           })
       }
    });
};

//author update get
exports.author_update_get = (req,res,next)=>{
    Author.findById(req.params.id,function (err, author) {
        if(err) return next(err);
        res.render('author_form',{title:'编辑作家',author})
    })
};

//author update post
exports.author_update_post = [
    body('first_name','firstName is required').trim().isLength({min:2}),
    body('family_name','family_name is required').trim().isLength({min:2}),
    body('date_of_birth','birth date is invalid').optional({checkFalsy:true}).isISO8601(),
    body('date_of_death','death date is invalid').optional({checkFalsy:true}).isISO8601(),
    sanitizeBody('first_name').escape(),
    sanitizeBody('family_name').escape(),
    sanitizeBody('date_of_birth').toDate(),
    sanitizeBody('date_of_death').toDate(),
    (req,res,next)=>{
        const errors = validationResult(req);
        const author = new Author({
            ...req.body,
            _id:req.params.id
        });
        if(!errors.isEmpty()){
            res.render('author_form',{title:'重新编辑作家',author,errors:errors.array()});
        }else{
            Author.findByIdAndUpdate(req.params.id,author,{},function (err, theAuthor) {
                if(err) return next(err);
                res.redirect(theAuthor.url);
            })
        }
    }
];

